package org.lemon.db.store;

/**
 * @since 2024-12-12 11:56
 */
public class Buffer {
    private FileManager fileManager;
    private LogManager logManager;
    private Page content;
    private BlockId blockId;
    private int pins;
    private int txnNum;
    private long lsn;

    public Buffer(FileManager fileManager, LogManager logManager) {
        this.fileManager = fileManager;
        this.logManager = logManager;
        this.txnNum = -1;
        this.content = Page.create(fileManager.getBlockSize());
    }

    public void setModified(int txnNum,long lsn){
        this.txnNum = txnNum;
        if(lsn > 0){
            this.lsn = lsn;
        }
    }

    public boolean isPined(){
        return this.pins > 0;
    }

    public void flush(){
        if(txnNum >= 0){
            logManager.flushByLSN(lsn);
            fileManager.write(blockId,getContent());
            content.reset();
            txnNum = -1;
        }
    }

    public void assignToBlock(BlockId blockId){
        this.flush();
        this.blockId = blockId;
        fileManager.read(blockId,getContent());
        pins = 0;
    }

    public void pin(){
        this.pins += 1;
    }

    public void  unpin(){
        this.pins -= 1;
    }


    public Page getContent() {
        return content;
    }

    public BlockId getBlockId() {
        return blockId;
    }

    public int getPins() {
        return pins;
    }

    public int getTxnNum() {
        return txnNum;
    }

    public long getLsn() {
        return lsn;
    }
}
